﻿#region Copyrights Notice
//©2010 Microsoft Corporation. All rights reserved.
#endregion

#region usings
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

using Microsoft.InformationSecurity.CISF.SecurityPortal.Business.Entities;
using Microsoft.InformationSecurity.CISF.SecurityPortal.Business.Widget;
using Microsoft.InformationSecurity.CISF.SecurityPortal.UI.WebLibrary;
using Microsoft.InformationSecurity.CISF.SecurityPortal.UI.Web.Widgets.MasterControls;

//Service Reference
using Microsoft.InformationSecurity.CISF.SecurityPortal.UI.Web.PortalService;
#endregion

namespace Microsoft.InformationSecurity.CISF.SecurityPortal.UI.Web
{
    public partial class PortalHomepage : PortalHomeBasePage
    {
        #region Instantiate

        //Get username from context
        string _UserName = Environment.UserName;
        private const int NoOfWidgetsInWidgetManager = 12;
        private WidgetSetup _UserWidgetSetup
        {
            get { return Context.Items[typeof(WidgetSetup)] as WidgetSetup; }
            set { Context.Items[typeof(WidgetSetup)] = value; }
        }

        private int AddMoretoThisPageWidgetListIndex
        {
            get { object val = ViewState["AddMoretoThisPageWidgetListIndex"]; if (val == null) return 0; else return (int)val; }
            set { ViewState["AddMoretoThisPageWidgetListIndex"] = value; }
        }
        private List<Widget> ControlList
        {
            get
            {
                //Get the Widget List from Cache or make the Service Call
                List<Widget> _widgets = Cache["Widgets"] as List<Widget>;
                if (null == _widgets)
                {
                    //Adding SOA Layer
                    PortalServiceClient wscProxy = new PortalServiceClient();
                     Widget[] widcol = wscProxy.GetWidgetList(_UserName);
                    wscProxy.Close();

                    _widgets = new List<Widget>(widcol.Count());
                    foreach (Widget widget in widcol)
                    {
                        _widgets.Add(widget);
                    }

                    //Cache the Widget List
                    Cache["Widgets"] = _widgets;
                }

                return _widgets;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        #region Load_WidgetFramework

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            this.ShowAddMoreWidgetsPanel();
            this.LoadUserWidgetSetup();
            // First visit, non postback            
            this.RenderWidgets(!ScriptManager.GetCurrent(Page).IsInAsyncPostBack);
        }

        private void ShowAddMoreWidgetsPanel()
        {
            if (this.AddMoreToThisPagePanel.Visible)
            {
                var itemsToShow = ControlList.Skip(AddMoretoThisPageWidgetListIndex * NoOfWidgetsInWidgetManager).Take(NoOfWidgetsInWidgetManager);
                this.WidgetDataList.DataSource = itemsToShow;
                this.WidgetDataList.DataBind();

                this.WidgetListPreviousLinkButton.Visible = AddMoretoThisPageWidgetListIndex > 0;
                this.WidgetListNextButton.Visible = AddMoretoThisPageWidgetListIndex * NoOfWidgetsInWidgetManager + NoOfWidgetsInWidgetManager < ControlList.Count;
            }
        }
        
        private void LoadUserWidgetSetup()
        {
            //Based on the User First Visit or Re-Visit; setup widgets for user
            //** Need to be updated to User Profile when that is available **//

            //Adding SOA Layer
            PortalServiceClient wscProxy = new PortalServiceClient();
            _UserWidgetSetup = wscProxy.LoadWidgetSetup(_UserName);
            wscProxy.Close();
        }
        private void RenderWidgets(bool isWidgetFirstLoad)
        {
            var setup = _UserWidgetSetup;

            Panel[] columnPanels = this.ThreeColPanelLayout.GetPanels();
            foreach (Panel panel in columnPanels)
            {
                List<ContainerUserControl> widgets = panel.Controls.OfType<ContainerUserControl>().ToList();
                foreach (var widget in widgets) panel.Controls.Remove(widget);
            }

            foreach (WidgetInstance instance in setup.WidgetInstances)
            {

                var panel = columnPanels[instance.TableColPos];
                ContainerUserControl widget = WidgetControlFactory.CreateControlHost(this) as ContainerUserControl;
                widget.ID = "WidgetHost" + instance.WidgetInstanceId.ToString();
                widget.FirstTime = isWidgetFirstLoad;
                widget.ac.WidgetInstanceControl = instance;
                widget.OnControlDelete += new Action<WidgetInstance>(widget_Deleted);
                try
                {
                    panel.Controls.Add(widget);
                }
                catch { }

            }
        }

        void widget_Deleted(WidgetInstance wi)
        {
            //Adding SOA Layer
            PortalServiceClient wscProxy = new PortalServiceClient();
            _UserWidgetSetup = wscProxy.GetWidgetSetup(_UserName);
            wscProxy.Close();

            this.RenderWidgets(!ScriptManager.GetCurrent(Page).IsInAsyncPostBack);
            this.RefreshAllWidgetColumns();
        }
        private void RefreshAllWidgetColumns()
        {
            this.UpdateWidgetPanel(0);
            this.UpdateWidgetPanel(1);
            this.UpdateWidgetPanel(2);
        }
        private void UpdateWidgetPanel(int columnNo)
        {
            this.ThreeColPanelLayout.UpdateWidgetPanel(columnNo);
        }

        #endregion

        #region PageEvents

        protected void AddMoreWidgets_Click(object sender, EventArgs e)
        {
            this.ResetHomePagePanel.Visible = false;
            this.AddMoreToThisPagePanel.Visible = !this.AddMoreToThisPagePanel.Visible;

            this.ShowAddMoreWidgetsPanel();
        }
        protected void ResetWidgets_Click(object sender, EventArgs e)
        {
            this.AddMoreToThisPagePanel.Visible = false;
            this.ResetHomePagePanel.Visible = !this.ResetHomePagePanel.Visible;

        }

        protected void ResetHomePageSave_Click(object sender, EventArgs e)
        {
            this.ResetHomePagePanel.Visible = false;

            //Starting over...
            //Adding SOA Layer
            PortalServiceClient wscProxy = new PortalServiceClient();
            _UserWidgetSetup = wscProxy.ResetWidgetSetup(_UserName);
            wscProxy.Close();

            //now refrsh the widgets in the UI
            this.RenderWidgets(!ScriptManager.GetCurrent(Page).IsInAsyncPostBack);
            this.RefreshAllWidgetColumns();
        }
        protected void ResetHomePageCancel_Click(object sender, EventArgs e)
        {
            this.ResetHomePagePanel.Visible = false;
            //do nothing...
        }
        protected void WidgetListPreviousLinkButton_Click(object sender, EventArgs e)
        {
            if (0 == this.AddMoretoThisPageWidgetListIndex)
                return;

            this.AddMoretoThisPageWidgetListIndex--;

            this.ShowAddMoreWidgetsPanel();
        }
        protected void WidgetListNextButton_Click(object sender, EventArgs e)
        {
            this.AddMoretoThisPageWidgetListIndex++;
            this.ShowAddMoreWidgetsPanel();
        }
        protected void WidgetDataList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Widget widget = e.Item.DataItem as Widget;

                CheckBox w = e.Item.Controls.OfType<CheckBox>().Single();

                w.Text = " " + widget.Name;
                w.ID = "AddWidget_" + widget.WidgetId.ToString();
                w.Attributes.Add("WidgetId", widget.WidgetId.ToString());
                w.Checked = IsWidgetSelected(widget.Name);
            }
        }
        private bool IsWidgetSelected(string widgetTitle)
        {
            var setup = _UserWidgetSetup;

            if(setup != null)
            {
                foreach (WidgetInstance instance in setup.WidgetInstances)
                {
                    if (instance.Caption.Equals(widgetTitle))
                        return true;
                }
            }
            return false;
        }

        protected void AddWidgetsSave_Click(object sender, EventArgs e)
        {
            this.AddMoreToThisPagePanel.Visible = false;

            //Get the selected widget list.
            WidgetSetup _newSetup = new WidgetSetup();
            //find datalist.
            IEnumerable<DataList> DataList = this.AddMoreToThisPagePanel.Controls.OfType<DataList>();

            DataListItemCollection items = DataList.OfType<DataList>().Single().Items;
            foreach (DataListItem i in items)
            {
                CheckBox c = i.Controls.OfType<CheckBox>().Single();

                if (c.Checked == true)
                {
                    Int32 id = Int32.Parse(c.Attributes["WidgetId"]);

                    //Find widget in the widget list.
                    Widget w = ControlList.Find(w1 => (w1.WidgetId == id));
                    //Construct WigetInstnace.
                    WidgetInstance wi = new WidgetInstance(w);
                    _newSetup.WidgetInstances.Add(wi);
                }
            }

            //Adding SOA Layer
            PortalServiceClient wscProxy = new PortalServiceClient();
            _UserWidgetSetup = wscProxy.UpdateWidgetSetup(_UserName,_UserWidgetSetup, _newSetup);
            wscProxy.Close();

            //now refrsh the widgets in the UI
            this.RenderWidgets(!ScriptManager.GetCurrent(Page).IsInAsyncPostBack);
            this.RefreshAllWidgetColumns();
        }
        protected void AddWidgetsCancel_Click(object sender, EventArgs e)
        {
            this.AddMoreToThisPagePanel.Visible = false;
        }

        #endregion


    }
}
